package cn.wolfcode.luowowo.resolver;

import cn.wolfcode.luowowo.annotation.CurrentUser;
import cn.wolfcode.luowowo.domain.User;
import cn.wolfcode.luowowo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

//把请求映射方法形式参数中贴有@CurrentUser的User参数,解析为当前登录用户对象
public class UserArgumentResolver  implements HandlerMethodArgumentResolver {

    @Autowired
    private IUserService userService;

    //这个方法用来说明该解析器支持什么类型的参数，返回布尔，true为支持，否则为不支持
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //形参贴有@CurrentUser    参数类型是User则    返回true，表示支持

        return parameter.getParameterAnnotation(CurrentUser.class) != null
                &&
                parameter.getParameterType() == User.class;
    }
    //解析参数的逻辑   上面那个是true才执行
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        //获取http请求对象
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        //获取token,查询当前登录用户
        //注入到形参中
        User currentUser = userService.getCurrentUser(request.getHeader("token"));
        return currentUser;
    }
}
